package com.dgut.uhrs.service;

import com.dgut.uhrs.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service(value = "userDetailsService")
public class UserDetailsServiceImp implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        if (s.length()==0||s==null){
            throw new RuntimeException("用户名不能为空!");
        }
        com.dgut.uhrs.bean.User user = userMapper.findUserByName(s);
        if (user==null){
            throw  new UsernameNotFoundException(String.format("用户不存在!",s));
        }
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        //获取用户角色名称
        List<String> roleCode = userMapper.getRoleCodeByUserName(s);

        for (String code : roleCode) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(code);
            grantedAuthorities.add(simpleGrantedAuthority);
        }
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        return new User( user.getName(),passwordEncoder.encode(user.getPassword()),grantedAuthorities);
    }
}
